﻿using Account.Api.Client;
using AutoMapper.Configuration;
using BlazorDownloadFile;
using Common.Api.Client;
using Cyss.Core;
using Cyss.Core.Api;
using Cyss.Core.Api.Client;
using Cyss.Core.Api.JWT;
using Cyss.Core.Cache;
using Cyss.Core.Infrastructure;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Order.Api.Client;
using System.Threading.Tasks;

namespace CyssBlazor.WebAssembly.ServerHost
{
    public static class ServicesExtensions
    {
        public static IServiceCollection AddServices(this IServiceCollection Services, Microsoft.Extensions.Configuration.IConfiguration configuration)
        {
            Services.RegisterCoreSerivce();
            Services.AddSingleton<ITokenHelper, TokenHelper>();


            Services.AddSingleton<IRedisConnectionWrapper, RedisConnectionWrapper>();
            Services.AddSingleton<IStaticCacheManager, RedisCacheManager>();

            Services.AddBlazorDownloadFile();

            Services.AddJsonOptions();
            Services.RegisterAllConfig(configuration);
            Services.RegisterClientConfig(configuration);

            Services.AddSingleton<IApiToken, ApiToken>();
            Services.RegisterAccountClient();
            Services.RegisterCommonClient();
            Services.RegisterOrderClient();

            //Services.AddScoped<IBlazorWorkContext, BlazorWorkContext>();


            return Services;
        }

    }

    public class ApiToken : IApiToken
    {
        public Task<string> GetTotkenAsync()
        {
            var httpContextAccessor = IOCEngine.Resolve<IHttpContextAccessor>();
            if (httpContextAccessor == null)
            {
                return Task.FromResult(string.Empty);
            }

            var tokenobj = httpContextAccessor.HttpContext.Request.Headers["ApiToken"];
            if (tokenobj.Count <= 0)
            {
                return Task.FromResult(string.Empty);
            }
            string token = tokenobj[0];
            return Task.FromResult(token);
        }
    }
}
